from flask import Flask, jsonify, send_file
from flask_cors import CORS
from utils.uart import SerialPortManager
from utils.Logger import logger
import time
from threading import Lock
import yaml

app = Flask(__name__, 
    static_folder='/',  # 指定静态文件夹的位置
    template_folder='/'  # 指定模板文件夹的位置
)
CORS(app)
class SerialDataAPI:
    def __init__(self):
        self.serial_manager = None
        # self.result = {}
        # self.result_lock = Lock()
        try:
            self.log_message({"message": "开始初始化串口管理器..."})
            self.serial_manager = SerialPortManager('config.yaml')
            # self.serial_manager.set_data_callback(self.on_data_received)
            self.serial_manager.start()
            self.log_message({"message": "串口初始化成功"})
            # self.result = self.serial_manager.parsed_data
            # return {"status": "success", "message": "串口初始化成功"}
        except Exception as e:
            logger.error(f"串口初始化失败: {e}")
            # return {"status": "error", "message": str(e)}

    def log_message(self, message: dict):
        logger.info(message)

    # def initialize_serial(self):
    #     """初始化串口管理器"""
        

    # def on_data_received(self, port_name: str, data: dict):
    #     """接收到串口数据时的回调函数"""
    #     try:
    #         with self.result_lock:
    #             self.result = data
    #             logger.info({
    #                 "on_data_received_value": self.result["2F"]["Second"]["更衣室"]["压差"]["value"],
    #                 "id": id(self.result)
    #             })
    #         return self.result
        # except Exception as e:
        #     logger.error(f"数据处理失败: {e}")

    def stop(self):
        """停止串口管理器"""
        if self.serial_manager:
            self.serial_manager.stop()

# 创建全局的API实例
serial_api = SerialDataAPI()
@app.route('/')
def index():
    return send_file('index.html')

def load_config():
    with open('config.yaml', 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)
def start_flask():
    config = load_config()
    server_config = config.get('server', {})
    
    host = server_config.get('host', '127.0.0.1')  # 默认值
    port = server_config.get('port', 5000)         # 默认值
    debug = server_config.get('debug', False)      # 默认值
    
    app.run(
        host=host,
        port=port,
        debug=debug
    )

@app.route('/data')
def get_result():
    try:
        # with serial_api.result_lock:
        value = serial_api.serial_manager.parsed_data["2F"]["Second"]["更衣室"]["压差"]["value"]
        logger.info({
            "get_result_value": value,
            # "id": id(serial_api.result)
        })
        logger.debug(serial_api.serial_manager.parsed_data)
        return jsonify(serial_api.serial_manager.parsed_data)
    except Exception as e:
        logger.error(f"获取数据失败: {e}")
        return jsonify({"error": str(e)})

if __name__ == '__main__':
    # 初始化串口
    # serial_api.initialize_serial()
    # 启动Flask应用
    start_flask()
